﻿using Oblivion.Networking;
using Oblivion.Networking.Encryptions;
using Oblivion.Networking.Packets;
using Oblivion.Substructure;

namespace Oblivion.Clients
{
    public class GameClient
    {
        private readonly Passport passport;

        public GameClient(Passport _passport)
        {
            passport = _passport;
        }

        public bool IsEncryptioned { get; set; }
        public byte[] SharedKey { get; set; }
        public string Hash { get; set; }

        public string Username { get; set; }
        public bool LoggedIn { get; set; }

        public AES Encryption { get; set; }

        public void SetupEncryption()
        {
            Encryption = new AES(SharedKey);
        }

        public void Send(byte[] data)
        {
            lock (data)
            {
                if (IsEncryptioned)
                    data = Encryption.Encrypt(data);
                if (passport.Socket.Connected)
                    passport.Socket.Send(data);
            }
        }

        public void Kick(string reason)
        {
            Send(new KickPacket {Reason = reason}.Build());

            DisconnectSocket();
        }

        /// <summary>
        /// Should only be used is special cases, please try to use the Kick method
        /// </summary>
        public void DisconnectSocket()
        {
            if (passport.Socket.Connected)
            {
                passport.Socket.Disconnect(false);
            }

            if (IsEncryptioned)
                IsEncryptioned = false;
            if (LoggedIn)
                LoggedIn = false;
            if (Kernel.ConnectedClients.Contains(this))
                Kernel.ConnectedClients.Remove(this);
        }
    }
}